<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <el-tab-pane label="角色管理">
            <!-- 左侧内容 -->
            <el-row
              style="height: 60px"
            ><el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="isDia"
            >新增角色</el-button></el-row>
            <!-- 表格 -->
            <el-table
              v-loading="isTab"
              stripe
              border
              align="center"
              :data="roleList"
            >
              <el-table-column
                label="序号"
                align="center"
                width="150%"
                type="index"
              />
              <el-table-column
                label="角色"
                prop="name"
                align="center"
                min-width="40%"
              />
              <el-table-column label="描述" prop="description" align="center" />
              <el-table-column label="操作" align="center">
                <!-- 通过饿了么Ui的插槽获取当前 所在列的id -->
                <template slot-scope="{ row }">
                  <el-button
                    size="small"
                    type="success"
                    @click="jurisdictionFn(row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="echoFn(row.id)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delFn(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 页码 -->
            <el-row style="margin-top: 30px">
              <el-col max-width="100%" align="end">
                <el-pagination
                  max-width="100%"
                  :page-sizes="sizes"
                  :page-size="page.pagesize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="page.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 右侧内容 -->
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              :closable="false"
              :show-icon="true"
            />
            <el-row style="margin-top: 50px">
              <el-col :span="8" :offset="1">
                <el-form label-width="80px" :model="firmlist">
                  <el-form-item label="公司名称">
                    <el-input v-model="firmlist.name" disabled />
                  </el-form-item>
                  <el-form-item label="公司地址">
                    <el-input v-model="firmlist.companyAddress" disabled />
                  </el-form-item>
                  <el-form-item label="公司邮箱">
                    <el-input v-model="firmlist.mailbox" disabled />
                  </el-form-item>
                  <el-form-item label="备注">
                    <el-input
                      v-model="firmlist.remarks"
                      type="textarea"
                      :rows="3"
                      disabled
                    />
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>

        <!-- 编辑 新增弹窗 -->
        <el-dialog
          :visible="showDialog"
          :title="formData.id ? '编辑角色' : '新增角色'"
          @close="closeFn"
        >
          <el-form
            ref="forms"
            label-width="100px"
            :model="formData"
            :rules="rules"
          >
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="formData.name" />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="formData.description" />
            </el-form-item>
          </el-form>
          <el-row type="flex" justify="center">
            <el-button @click="isDia">取 消</el-button>
            <el-button type="primary" @click="nweEditFn">确 定</el-button>
          </el-row>
        </el-dialog>

        <!-- 分配权限弹层 -->
        <Jurisdiction ref="justify" :dialog-visible.sync="isDialog" />
      </el-card>
    </div>
  </div>
</template>

<script>
import Jurisdiction from './components/jurisdiction.vue'
import { getDepartments } from '@/utils'
import { mapGetters } from 'vuex'
import {
  getRoleListApi,
  deleteRoleApi,
  getFirmListApi,
  getRoleDetailsApi,
  reviseRoleApi,
  addRoleApi,
  getPermissionListApi
} from '@/api'
export default {
  components: {
    Jurisdiction
  },
  data() {
    return {
      roleList: [], // 角色列表
      page: {
        page: 1, // 页码
        pagesize: 10, // 每页条数
        total: 0 // 数据总数
      },
      isTab: false, // Tab弹层加载状态
      sizes: [], // 可切换的每页条数
      firmlist: {}, // 公司数据
      showDialog: false, // 编辑 新增弹出框状态
      formData: {
        name: '',
        description: ''
      }, // 表单数据
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      }, // 校验规则
      isDialog: false // 分配权限弹出窗状态
    }
  },
  computed: {
    // 引入 vuex中 Getters内的快捷访问
    ...mapGetters(['companyId'])
  },
  created() {
    this.getRoleList()
    this.getFirmList()
  },
  methods: {
    // 获取所有数据
    async getRoleList() {
      this.isTab = !this.isTab
      const result = await getRoleListApi(this.page)
      this.roleList = result.rows
      this.isTab = !this.isTab
      // 数据条数同步给页码
      this.page.total = result.total
      // 处理选择显示数
      this.sizes = []
      // 向上取整
      const k = Math.ceil(this.page.total / 10)
      for (let i = 0; i < k; i++) {
        this.sizes.push((i + 1) * 10)
      }
    },

    // 点击切换每页显示条数 触发
    handleSizeChange(val) {
      // 每页显示页数
      this.page.pagesize = val
      this.getRoleList()
    },

    // 页码变化时触发
    async handleCurrentChange(val) {
      this.page.page = val
      this.getRoleList()
    },

    // 点击 -> 删除角色
    async delFn(id) {
      try {
        // 点击确定会往后执行 Promise返回正确结果才会执行后面的代码
        await this.$confirm('确定删除此角色?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteRoleApi(id)
        // 刷新数据
        this.getRoleList()
        this.$message.success('删除成功!')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取公司信息
    async getFirmList() {
      // 铺设公司信息
      try {
        this.firmlist = await getFirmListApi(this.companyId)
      } catch (error) {
        console.log(error)
      }
      console.log(this.firmlist)
    },

    // 新增 编辑 窗口关闭触发
    closeFn() {
      this.formData = {
        name: '',
        description: ''
      }
      this.$refs.forms.resetFields()
      this.showDialog = false
    },
    // 点击 弹出或者关闭弹出框
    isDia() {
      this.showDialog = !this.showDialog
    },
    // 编辑数据回显
    async echoFn(id) {
      this.formData = await getRoleDetailsApi(id)
      this.showDialog = true
    },

    // 点击 -> 判断是否是新增按钮
    async nweEditFn() {
      try {
        await this.$refs.forms.validate()
        if (this.formData.id) {
          await reviseRoleApi(this.formData) // 请求更新数据
          this.$message.success('编辑成功')
        } else {
          await addRoleApi(this.formData)
          this.$message.success('修改完成')
        }
        this.getRoleList() // 重置数据
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },

    // 点击 -> 分配权限
    async jurisdictionFn(id) {
      // 将 所有权限获取处理 并传给子组件渲染
      this.$refs.justify.list = getDepartments(await getPermissionListApi(), '0')
      // 获取当前角色的权限
      const { permIds } = await getRoleDetailsApi(id)
      this.$refs.justify.defaultChecked = permIds
      // 将当前点击的角色id传给子组件
      this.$refs.justify.userId = id
      this.isDialog = true
    }
  }
}
</script>

<style lang="scss" scoped></style>
